package com.lanlian.cayman.fragment;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.lanlian.cayman.LLApplication;
import com.lanlian.cayman.R;
import com.lanlian.cayman.activity.LoginActivity;
import com.lanlian.cayman.activity.RegisterMobileActivity;
import com.lanlian.cayman.activity.RiskStateActivity;
import com.lanlian.cayman.activity.TradeDocumentaryActivity;
import com.lanlian.cayman.activity.UpdateRegisterAgreementActivity;
import com.lanlian.cayman.view.RiskInvestigationDialog;
import com.lanlian.commonlib.base.BaseFragment;
import com.lanlian.commonlib.event.EventCode;
import com.lanlian.commonlib.event.EventMessage;
import com.lanlian.commonlib.util.EventBusUtils;
import com.lanlian.commonlib.util.OnEventID;
import com.lanlian.commonlib.util.OnEventUtils;
import com.lanlian.uikit.CustomDialog;
import com.lanlian.utillib.DisplayUtil;

import net.lucode.hackware.magicindicator.MagicIndicator;
import net.lucode.hackware.magicindicator.ViewPagerHelper;
import net.lucode.hackware.magicindicator.buildins.commonnavigator.CommonNavigator;
import net.lucode.hackware.magicindicator.buildins.commonnavigator.abs.CommonNavigatorAdapter;
import net.lucode.hackware.magicindicator.buildins.commonnavigator.abs.IPagerIndicator;
import net.lucode.hackware.magicindicator.buildins.commonnavigator.abs.IPagerTitleView;
import net.lucode.hackware.magicindicator.buildins.commonnavigator.indicators.LinePagerIndicator;
import net.lucode.hackware.magicindicator.buildins.commonnavigator.titles.ColorTransitionPagerTitleView;

import java.util.ArrayList;

/**
 * <pre>
 *     author : huxiaobo
 *     e-mail : xiaobo.hu@foxtry.com
 *     date   : 2018/8/9 13:40
 *     desc   : 交易TAB
 *     version: 1.0
 * </pre>
 */
public class TradeFragment extends BaseFragment implements View.OnClickListener {

    private String[] mTitleList = new String[]{"持仓", "委托", "我的跟单", "排行榜"};
    private ArrayList<Fragment> mFragments = new ArrayList<>();

    private TextView mTvDocumentary;
    private TextView mTvAction;
    private LinearLayout mLayNoLogin;
    private TextView mTvLogin;
    private TextView mTvRegister;
    private LinearLayout mLayLogin;
    private MagicIndicator mMagicIndicator;
    private ViewPager mViewPager;
    private TextView mTvPositionPnl;
    private TextView mTvAvailableFunds;
    private TextView mTvDeposit;
    private TextView mTvOvernightDeposit;
    private TextView mTvDepositType;
    private int accountType;
    private boolean mIsUIVisible;

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        mIsUIVisible = !hidden;
        if (!hidden) {
            if (mDBManager.isLogined()) {
                EventBusUtils.post(new EventMessage(EventCode.EVENT_FUNDS_REFRESH));
            }
        }
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_trade, null);
        mIsUIVisible = true;
        initView(view);
        setListeners();
        initFragments();
        initNavigator();
        setLoginLayout();
        return view;
    }


    @Override
    protected void initView(View view) {
        super.initView(view);
        mTvDocumentary = view.findViewById(R.id.tv_documentary);
        mTvAction = view.findViewById(R.id.tv_action);
        mLayNoLogin = view.findViewById(R.id.lay_no_login);
        mTvLogin = view.findViewById(R.id.tv_login);
        mTvRegister = view.findViewById(R.id.tv_register);
        mLayLogin = view.findViewById(R.id.lay_login);
        mMagicIndicator = view.findViewById(R.id.magic_indicator);
        mViewPager = view.findViewById(R.id.view_pager);
        mTvPositionPnl = view.findViewById(R.id.tv_position_pnl);
        mTvAvailableFunds = view.findViewById(R.id.tv_available_funds);
        mTvDeposit = view.findViewById(R.id.tv_deposit);
        mTvOvernightDeposit = view.findViewById(R.id.tv_overnight_deposit);
        mTvDepositType = view.findViewById(R.id.tv_deposit_type);
    }

    @Override
    protected void setListeners() {
        super.setListeners();
        mTvDocumentary.setOnClickListener(this);
        mTvAction.setOnClickListener(this);
        mTvRegister.setOnClickListener(this);
        mTvLogin.setOnClickListener(this);
        mViewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int i, float v, int i1) {
            }

            @Override
            public void onPageSelected(int i) {
                switch (i) {
                    case 0:
                        mTvAction.setText("全部平仓");
                        break;
                    case 1:
                        mTvAction.setText("全部撤单");
                        break;
                    default:
                        mTvAction.setText("");
                        break;
                }
            }

            @Override
            public void onPageScrollStateChanged(int i) {
            }
        });
    }

    private void initFragments() {
        mFragments.add(new TradePositionFragment());
        mFragments.add(new TradeEntrustFragment());
        mFragments.add(new TradeDocumentaryFragment());
        mFragments.add(new TradeChartsFragment());
    }

    private void initNavigator() {
        CommonNavigator commonNavigator = new CommonNavigator(getActivity());
        commonNavigator.setAdjustMode(true);
        commonNavigator.setAdapter(new CommonNavigatorAdapter() {

            @Override
            public int getCount() {
                return mTitleList == null ? 0 : mTitleList.length;
            }

            @Override
            public IPagerTitleView getTitleView(Context context, final int index) {
                ColorTransitionPagerTitleView colorTransitionPagerTitleView = new ColorTransitionPagerTitleView(context);
                colorTransitionPagerTitleView.setNormalColor(getResources().getColor(R.color.color_8893B0));
                colorTransitionPagerTitleView.setTextSize(13);
                colorTransitionPagerTitleView.setSelectedColor(getResources().getColor(R.color.color_K4));
                colorTransitionPagerTitleView.setText(mTitleList[index]);
                colorTransitionPagerTitleView.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        mViewPager.setCurrentItem(index);
                    }
                });
                return colorTransitionPagerTitleView;
            }

            @Override
            public IPagerIndicator getIndicator(Context context) {
                LinePagerIndicator indicator = new LinePagerIndicator(context);
                indicator.setMode(LinePagerIndicator.MODE_EXACTLY);
                indicator.setColors(getResources().getColor(R.color.color_K4));
                indicator.setLineWidth(DisplayUtil.dip2px(context, 24));
                indicator.setRoundRadius(DisplayUtil.dip2px(context, 1));
                indicator.setLineHeight(DisplayUtil.dip2px(context, 2));
                return indicator;
            }
        });
        mMagicIndicator.setNavigator(commonNavigator);
        ViewPagerHelper.bind(mMagicIndicator, mViewPager);
        mViewPager.setAdapter(new FragmentPagerAdapter(getChildFragmentManager()) {
            @Override
            public Fragment getItem(int position) {
                return mFragments.get(position);
            }

            @Override
            public int getCount() {
                return mFragments.size();
            }
        });
        mViewPager.setOffscreenPageLimit(mFragments.size());
    }

    /**
     * 设置登录与未登录的布局
     */
    private void setLoginLayout() {
        if (mDBManager.isLogined()) {
            mTvAction.setVisibility(View.VISIBLE);
            mTvDocumentary.setVisibility(View.VISIBLE);
            mLayNoLogin.setVisibility(View.GONE);
            mLayLogin.setVisibility(View.VISIBLE);
            if (mDBManager.getUser() != null && mDBManager.getUser().getAccountType() == 1) {
                mTvDepositType.setText("维持保证金");
                accountType = 1;
            } else {
                mTvDepositType.setText("隔夜保证金");
                accountType = 0;
            }
            setFunds();
        } else {
            mTvAction.setVisibility(View.GONE);
            mTvDocumentary.setVisibility(View.GONE);
            mLayNoLogin.setVisibility(View.VISIBLE);
            mLayLogin.setVisibility(View.GONE);
        }
    }

    @Override
    public void onClick(View view) {
        int id = view.getId();
        switch (id) {
            case R.id.tv_documentary:
                if (mDBManager.isLogined()) {
                    if (mDBManager.getUser() != null && mDBManager.getUser().getRiskAuthState() == 0 &&
                            mDBManager.getIsOldUser() == 0) {
                        new RiskInvestigationDialog(getActivity(), new RiskInvestigationDialog.OnClickListener() {
                            @Override
                            public void onWriteClick() {
                                startActivity(new Intent(getActivity(), RiskStateActivity.class)
                                        .putExtra("mobile", mDBManager.getUser().getMobileNo()));
                            }

                            @Override
                            public void onCloseClick() {
                            }
                        }).show();
                        return;
                    }
                    startActivity(new Intent(getActivity(), TradeDocumentaryActivity.class));
                } else {
                    startActivity(new Intent(getActivity(), LoginActivity.class));
                }
                break;
            case R.id.tv_action:
                switch (mTvAction.getText().toString()) {
                    case "全部平仓":
                        if (isPingcangAllFastClick()) {
                            return;
                        }
                        TradePositionFragment positionFragment = (TradePositionFragment) mFragments.get(0);
                        if (positionFragment.mList == null || positionFragment.mList.size() == 0) {
                            showToast("您当前未持仓！");
                            return;
                        }
                        OnEventUtils.onEvent(getActivity(), OnEventID.CLEAR_POSITION);
                        new CustomDialog(getActivity(), new CustomDialog.OnClickListener() {
                            @Override
                            public void onLeftClick() {
                            }

                            @Override
                            public void onRightClick() {
                                if (!isFastClick()) {
                                    positionFragment.pingCangAll();
                                }
                            }
                        }).setTitle("全部平仓").setContent("您确认将所有持仓合约平仓吗？").show();
                        break;
                    case "全部撤单":
                        TradeEntrustFragment entrustFragment = (TradeEntrustFragment) mFragments.get(1);
                        if (entrustFragment.mList == null || entrustFragment.mList.size() == 0 || !entrustFragment.iscancleAll()) {
                            showToast("无可撤销委托合约！");
                            return;
                        }
                        new CustomDialog(getActivity(), new CustomDialog.OnClickListener() {
                            @Override
                            public void onLeftClick() {
                            }

                            @Override
                            public void onRightClick() {
                                entrustFragment.cancleAll();
                            }
                        }).setTitle("全部撤单").setContent("您确认将所有委托合约撤销吗？").show();
                        break;
                    default:
                        break;
                }
                break;
            case R.id.tv_login:
                startActivity(new Intent(getActivity(), LoginActivity.class));
                break;
            case R.id.tv_register:
                OnEventUtils.onEvent(getActivity(), OnEventID.OPEN_ACCOUNT);
                startActivity(new Intent(getActivity(), RegisterMobileActivity.class));
                break;
            default:
                break;
        }
    }

    private void setFunds() {
        if (accountType == 1) {
            mTvOvernightDeposit.setText(String.format("$ %.2f", LLApplication.getUnitAssetInfo().getKeepBzj()));
        } else {
            mTvOvernightDeposit.setText(String.format("$ %.2f", LLApplication.getOvernightDeposit()));
        }
        mTvAvailableFunds.setText(String.format("$ %.2f", LLApplication.getAvailableFunds()));
        mTvDeposit.setText(String.format("$ %.2f", LLApplication.getDeposit()));
        mTvPositionPnl.setText(String.format("$ %.2f", LLApplication.getPositionPnl()));
    }

    @Override
    protected boolean isRegisteredEventBus() {
        return true;
    }

    @Override
    public void onReceiveEvent(EventMessage event) {
        super.onReceiveEvent(event);
        switch (event.getCode()) {
            case EventCode.EVENT_LOGIN_REFRESH:
                setLoginLayout();
                if (mIsUIVisible) {
                    if (mDBManager.getIsOldUser() == 1) {
                        new CustomDialog(getActivity(), new CustomDialog.OnClickListener() {
                            @Override
                            public void onLeftClick() {
                            }

                            @Override
                            public void onRightClick() {
                                startActivity(new Intent(getActivity(), UpdateRegisterAgreementActivity.class)
                                        .putExtra("mobile", mDBManager.getUser().getMobileNo()));
                            }
                        }).setContent("尊敬的客户，为了给您提供更完善的交易服务，请您完善账户资料补充申请（通讯地址、资产职业信息），感谢您的配合！")
                                .setLeft("稍后").setRight("进入").setGravity(Gravity.LEFT).show();
                    } else if (mDBManager.getUser().getRiskAuthState() == 0) {
                        new RiskInvestigationDialog(getActivity(), new RiskInvestigationDialog.OnClickListener() {
                            @Override
                            public void onWriteClick() {
                                startActivity(new Intent(getActivity(), RiskStateActivity.class)
                                        .putExtra("mobile", mDBManager.getUser().getMobileNo()));
                            }

                            @Override
                            public void onCloseClick() {
                            }
                        }).show();
                    }
                }
                break;
            case EventCode.EVENT_LOGIN_OUT_REFRESH:
                setLoginLayout();
                break;
            case EventCode.EVENT_MARKET:
                setFunds();
                break;
            case EventCode.EVENT_FRAGMENT_POSITION:
                mViewPager.setCurrentItem(0);
                break;
            case EventCode.EVENT_FUNDS_REFRESH:
                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        setFunds();
                    }
                }, 3000);
                break;
            default:
                break;
        }
    }

    private static final int MIN_DELAY_TIME = 1000;  // 两次点击间隔不能少于1000ms
    private long lastPingcangAllClickTime;

    public boolean isPingcangAllFastClick() {
        boolean flag = true;
        long currentClickTime = System.currentTimeMillis();
        if ((currentClickTime - lastPingcangAllClickTime) >= MIN_DELAY_TIME) {
            flag = false;
            lastPingcangAllClickTime = currentClickTime;
        }
        return flag;
    }

}
